# -*- encoding=utf8 -*-

__author__ = "code"
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from airtest.cli.parser import cli_setup

poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)

if not cli_setup():
    auto_setup(__file__, logdir=None, devices=[
#         "Android://127.0.0.1:5037/e9bd483?cap_method=JAVACAP&&ori_method=ADBORI",
        "Android://127.0.0.1:5037/M960BDPT226TA?cap_method=JAVACAP&&ori_method=ADBORI",
    ])


def start():
    home()
    stop_app('com.example.getwifiip')
    sleep(1)
    start_app('com.example.getwifiip')
    sleep(2)
    edit_serve_ip = poco(type="android.widget.EditText", name="com.example.getwifiip:id/edit_serve_ip")
    confirm_btn = poco(type="android.widget.Button", name="com.example.getwifiip:id/confirm_btn")
    show_ip = poco(type="android.widget.TextView", name="com.example.getwifiip:id/show_ip")

    if edit_serve_ip.exists() and show_ip.exists() and confirm_btn.exists():
        ip_value = show_ip.get_text()
        # 读取服务启动ip
        ip_list = serve_ip()
        if len(ip_list) > 0:
            edit_serve_ip.set_text("%s/api/reg_wifi_devices?client=%s" % (ip_list[0], ip_value,))
            # 注册服务
            confirm_btn.click()


def serve_ip() -> []:
    ip_list = []
    path = '{path}/conf/serve_ip_wifi.conf'.format(
        path=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    with open(path) as f:
        for line in f.readlines():
            if len(line.strip()) > 0 and len(line.replace("\r", "").replace("\n", "").replace("\r\n", "")) > 0:
                ip_list.append(line.replace("\r", "").replace("\n", "").replace("\r\n", ""))
    return ip_list


def main():
    try:
        start()
    except Exception as e:
        print(e)


if __name__ == '__main__':
    main()
